package org.wz.complex.work.controller.project.generator;

import jakarta.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.wz.complex.work.bean.Res;
import org.wz.complex.work.controller.base.BaseController;
import org.wz.complex.work.entity.project.code.CodeJava;
import org.wz.complex.work.entity.project.database.DatabaseName;
import org.wz.complex.work.entity.project.database.DatabaseSource;
import org.wz.complex.work.entity.project.generator.GeneratorJava;
import org.wz.complex.work.kit.code.GeneratorJavaKit;
import org.wz.complex.work.service.auth.sysinfo.SysinfoMicroService;
import org.wz.complex.work.service.project.code.CodeJavaService;
import org.wz.complex.work.service.project.database.DatabaseNameService;
import org.wz.complex.work.service.project.database.DatabaseSourceService;
import org.wz.complex.work.service.project.generator.GeneratorJavaService;


@RestController
@RequestMapping("/project/generator/java")
public class GeneratorJavaController extends BaseController<GeneratorJava, Object> {

    @Resource
    private GeneratorJavaService service;

    @Resource
    private SysinfoMicroService sysinfoMicroService;

    @Resource
    private CodeJavaService codeJavaService;

    @Resource
    private DatabaseNameService databaseNameService;

    @Resource
    private DatabaseSourceService databaseSourceService;

    @Transactional
    @PostMapping("/generate")
    public Res generate(@RequestBody GeneratorJava gen) throws Exception {

        CodeJava project = gen.getCodeJava();
        if (null != project) {
            // 设置 DatabaseName
            Long nameId = project.getParentId();
            if (null != nameId) {
                DatabaseName nameInfo = databaseNameService.getById(nameId);
                project.setDatabaseName(nameInfo);
                // 设置 DatabaseSource
                Long sourceId = nameInfo.getParentId();
                if (null != sourceId) {
                    DatabaseSource sourceInfo = databaseSourceService.getById(sourceId);
                    nameInfo.setDatabaseSource(sourceInfo);
                }
            }
        }

        // 生成代码
        GeneratorJavaKit.generate(gen);

        // 保存数据库
        if (gen.getStatus() != null && gen.getStatus() == 1) {
            // insert
            gen.setId(null);
            service.saveOrUpdate(gen);
        }
        return Res.ok(1);
    }

}



